<template>
  <div class="search">

    <div class="search-container">
      <!-- 输入框 + 查询按钮 -->
      <el-input v-model="searchForm.keyword" placeholder="输入员工编号/姓名/手机号查询" clearable
        style="width: 300px; margin-right: 10px;" />
      <el-button type="primary" @click="searchStaff">查询</el-button>

      <!-- 复选框 + 职员管理链接 -->
      <el-checkbox v-model="searchForm.status" @change="handleCheck" style="margin-left: 20px;">显示禁用职员</el-checkbox>

      <!-- 操作按钮组 -->
      <div class="search-right">
        <el-button type="primary" @click="openAddDialog">新增</el-button>
        <el-button plain>导入</el-button>
        <el-button plain>导出</el-button>
        <el-button plain @click="refresh">刷新</el-button>
      </div>
    </div>


    <el-dialog v-model="dialogFormVisible" :title="dialogType === 'add' ? '新增职员' : '编辑职员'" width="500">
      <el-form :model="form">
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="部门" :label-width="formLabelWidth">
          <el-select v-model="form.departmentId" placeholder="请选择部门">
            <el-option v-for="item in departments" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" :label-width="formLabelWidth">
          <el-input v-model="form.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item v-if="dialogType === 'add'" label="身份证号码" :label-width="formLabelWidth">
          <el-input v-model="form.idCard" autocomplete="off" />
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth">
          <el-radio-group v-model="form.sex" style="display: inline-block;">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户角色" :label-width="formLabelWidth">
          <el-select v-model="form.roleIds" multiple placeholder="请选择角色" size="small" style="width: 100%">
            <el-option v-for="item in roles" :key="item.id" :label="item.roleName" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitStaff">
            确认
          </el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <el-table :data="tableData" border style="width: 100%" stripe>
    <el-table-column type="index" label="序号" />
    <el-table-column prop="name" label="姓名" />
    <el-table-column prop="code" label="员工编号" />
    <el-table-column prop="departmentId" label="所属部门">
      <template #default="scope">
        {{departments.find(item => item.id === scope.row.departmentId)?.name || ''}}
      </template>
    </el-table-column>
    <el-table-column prop="idCard" label="身份证号码" />
    <el-table-column label="角色">
      <template #default="scope">
        <span>
          {{
            scope.row.roleIds
              ?.map(id => roles.find(r => r.id === id)?.roleName)
              .join('，') || ''
          }}
        </span>
      </template>
    </el-table-column>

    <el-table-column prop="loginName" label="用户名" />

    <el-table-column prop="phone" label="联系方式" />
    <el-table-column prop="status" label="状态">
      <template #default="{ row }">
        <el-switch :model-value="row.status" :active-value="1" :inactive-value="0" :disabled="row.boss"
          @change="() => handleStatusChange(row)" />
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <template v-if="!scope.row.boss">
          <el-button class="!ml-0" icon="Edit" size="small" type="primary" @click="updateStaff(scope.row.id)" />
          <el-button type="primary" icon="Delete" size="small" @click="del(scope.row.id)" />
        </template>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <div class="demo-pagination-block" style="float: right;">
    <el-pagination v-model:current-page="pageInfo.pageNum" v-model:page-size="pageInfo.pageSize"
      :page-sizes="[5, 10, 15, 20]" :background="true" layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const dialogFormVisible = ref(false)
const dialogType = ref('add')
const formLabelWidth = '100px'

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: 1,
})

// 添加表单
const form = ref({
  name: '',
  departmentId: null,
  phone: '',
  idCard: '',
  sex: 1, // 默认男
  roleIds: [],
})


const pageInfo = reactive({
  total: 0,
  pageNum: 1,
  pageSize: 10
})

// 表格数据
const tableData = ref([])

// 部门数据
const departments = ref([])

// 角色数据
const roles = ref([])

// 获取所有部门
const getDepartments = async () => {
  const res = await axios.get("/api/basic/enterprise/allDepartment")
  if (res.data.code === 5200) {
    departments.value = res.data.departmentList
    
  } else {
    ElMessage.error(res.data.msg)
  }
}

// 获取角色
const getRoles = async () => {
  const res = await axios.get("/api/basic/enterprise/allRoles")
  if (res.data.code === 5200) {
    roles.value = res.data.roleList
  } else {
    ElMessage.error(res.data.msg)
  }
}


// 员工分页
const getStaffList = async () => {
  try {
    const res = await axios.get("/api/basic/enterprise/staffByPage", {
      params: {
        pageNum: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
        ...searchForm
      }
    })

    if (res.data.code === 5200) {
      tableData.value = res.data.pageInfo.list
      pageInfo.total = res.data.pageInfo.total
      pageInfo.pageNum = res.data.pageInfo.pageNum
    } else {
      ElMessage.error('获取员工列表失败')
    }
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('加载失败')
  }
}

const handleCheck = (checked) => {
  searchForm.status = checked ? null : 1
  getStaffList()
}

// 对话框
const openAddDialog = () => {
  form.value = { name: '', departmentId: null, phone: '', idCard: '', sex: 1, rolesId: [], companyCode: '' }
  dialogFormVisible.value = true
}

const updateStaff = async (id) => {
  dialogType.value = 'edit'
  const res = await axios.get('/api/basic/enterprise/staffById', { params: { id } })

  if (res.data.code === 5200) {
    const staff = res.data.staff
    form.value = {
      ...staff,
      departmentId: (staff.boss || staff.departmentId === '0') ? null : staff.departmentId
    }

    dialogFormVisible.value = true
  } else {
    ElMessage.error('获取数据失败')
  }
}
const searchStaff = () => {
  pageInfo.pageNum = 1
  getStaffList()
}

const submitStaff = async () => {
  // const { name, region, phone, idCard, rolesId } = form
  // const pattern = /^1[3-9]\d{9}$/
  // if (!name.trim()) {
  //   ElMessage.warning('请输入姓名')
  //   return
  // }
  // if (!region) {
  //   ElMessage.warning('请选择部门')
  //   return
  // }
  // if (!phone.trim()) {
  //   ElMessage.warning('请输入联系方式')
  //   return
  // }
  // if (!pattern.test(phone)) {
  //   ElMessage.warning('请输入正确的手机号码')
  //   return
  // }

  try {

    const url = dialogType.value === 'add' ? '/api/basic/enterprise/addStaff' : '/api/basic/enterprise/updateStaff'

    const res = await axios.post(url, form.value)

    if (res.data.code === 5200) {
      ElMessage.success(res.data.msg)
      dialogFormVisible.value = false
      await getStaffList()
    } else {
      ElMessage.error(res.data.msg || '操作失败')
    }
  } catch (error) {
    ElMessage.error('请求失败')
  }
}

const handleSizeChange = async (val) => {
  pageInfo.pageSize = val
  pageInfo.pageNum = 1
  await getStaffList()
}

const handleCurrentChange = async (val) => {
  pageInfo.pageNum = val
  await getStaffList()
}

const del = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除该员工吗？此操作不可恢复')

    const res = await axios.post('/api/basic/enterprise/deleteStaff', null, { params: { id } })

    if (res.data.code === 5200) {
      ElMessage.success(res.data.msg)
      getStaffList()
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    if (error === 'cancel' || error?.message === 'cancel') {
      console.log('用户取消了删除操作')
    } else {
      ElMessage.error('删除操作出现错误: ' + (error.response?.data?.msg || error.message))
    }
  }
}

//状态切换
const handleStatusChange = async (row) => {

  // const originalStatus = row.status
  try {
    const res = await axios.post('/api/basic/enterprise/updateStaffStatus', null, {
      params: { id: row.id }
    })
    if (res.data.code !== 5200) {
      ElMessage.error('状态更新失败')
    } else {
      ElMessage.success('状态更新成功')
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试')
  } finally {
    await getStaffList();
  }
}



// 刷新
const refresh = () => {
  // 重置表单
  searchForm.keyword = ''
  searchForm.showDisabled = false

  // 重新查询（此时会显示默认启用列表）
  searchStaff()
}

onMounted(() => {
  getDepartments()
  getRoles()
  getStaffList()
})

</script>

<style scoped>
/* 搜索表单 */

.search-container {
  display: flex;
  align-items: center;
  gap: 10px;
  /* 控制元素之间的间距 */
  padding: 10px 0;
  overflow-x: auto;
  /* 如果内容超出屏幕宽度，允许水平滚动 */
}

/* 确保操作按钮组与左侧元素对齐 */
.search-right {
  margin-left: auto;
  /* 将右侧按钮组推到最右边 */
  display: flex;
  gap: 10px;
}

/* 复选框与链接样式 */
.search-container .el-checkbox {
  margin-left: auto;
  /* 自动边距将复选框推到中间 */
}

.search-container .el-link {
  font-size: 12px;
  color: #409eff;
}


.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>